<template>
  <div class="app-container">
    <ViewSessions
      class="sousuo"
      style="margin-bottom: 15px"
      @selected="selected"
      @add="add"
    />
    <el-table
      :row-class-name="tableRowClassName"
      :data="orderList"
      :header-row-style="{
        'background-color': '#E6E6E6',
        'font-weight': 'bold',
        color: '#333',
      }"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      align="center"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
    >
      <el-table-column show-overflow-tooltip align="center" width="50px" prop="id" label="编号"/>
      <el-table-column align="center" label="订单二维码">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="() => seeVueQr(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" prop="uploadTime" label="上传时间"/>
      <el-table-column show-overflow-tooltip align="center" prop="startTime" label="计划开始时间"/>
      <el-table-column align="center" label="产品详情">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="() => seeOrder(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" prop="endTime" label="计划完成时间"/>
      <el-table-column show-overflow-tooltip align="center" prop="salesman" label="业务员"/>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <span>{{ scope.row.deleteFlag == 1 ? '删除' : '正常' }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" prop="deleteRemark" label="备注"/>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.deleteFlag == 1"
            type="text"
            size="mini"
            @click="() => seeDeleteItem(scope.row)"
          >查看
          </el-button>
          <el-button
            v-if="scope.row.deleteFlag != 1"
            type="text"
            size="mini"
            @click="() => upload(scope.row)"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.deleteFlag != 1"
            type="text"
            size="mini"
            @click="() => delect(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      style="padding: 30px 0; text-align: end"
      layout="total, prev, pager, next,jumper"
      @current-change="fetchData"
    />
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="dialogFormValue"
      @close="closeDialog"
    >
      <el-form
        ref="order"
        :model="order"
        :rules="validateRules"
        label-width="120px"
      >
        <!-- <el-form-item label="订单编号：" prop="code">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.code"
              size="small"
              placeholder="请输入订单编号"
            />
          </el-col>
        </el-form-item> -->
        <el-form-item label="计划开始时间：" prop="startTime">
          <el-col :span="6">
            <el-date-picker
              :disabled="readonlyInput"
              v-model="order.startTime"
              :picker-options="startDatePicker"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择计划开始时间："
            />
          </el-col>
        </el-form-item>
        <el-form-item label="计划完成时间：" prop="endTime">
          <el-col :span="6">
            <el-date-picker
              :disabled="readonlyInput"
              :picker-options="endDatePicker"
              v-model="order.endTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择计划完成时间："
            />
          </el-col>
        </el-form-item>
        <el-form-item label="产品：" prop="product">
          <el-col :span="15">
            <el-select
              :disabled="readonlyInput"
              v-model="order.product"
              clearable
              multiple
              placeholder="请选择产品"
              @change="changeProduct"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.id"
                :value="item.id"
              />
            </el-select>

          </el-col>
        </el-form-item>
        <div v-if="productSelectItem.length > 0">
          <div v-for="(item,index) in productSelectItem" :key="index" style="margin-left: 100px;">
            <div style="display: inline-flex;margin: 10px;">
              <span style="margin: 10px 10px;">{{ item.id }}</span>
              <el-input v-model="item.amount" placeholder="请输入产品数量"/>
            </div>
          </div>
        </div>
        <!-- <el-form-item label="产品数量：" prop="productNum">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.productNum"
              size="small"
              placeholder="请输入产品数量"
            />
          </el-col>
        </el-form-item> -->
        <el-form-item label="业务员：" prop="salesman">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.salesman"
              size="small"
              placeholder="请输入业务员"
            />
            <!-- <el-select v-model="order.salesman" clearable placeholder="请选择业务员">
                  <el-option
                    v-for="item in salesmanList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                   </el-option>
              </el-select> -->
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="restData()">取 消</el-button>
        <el-button type="primary" @click="append('order')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogDelect"
    >
      <el-input
        :rows="2"
        v-model="textDelect"
        type="textarea"
        placeholder="请输入删除理由"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="delectClick">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVueQr"
      width="400px"
    >
      <div style="text-align: center;height: 220px;">
        <vue-qr :size="191" :margin="0" :auto-color="true" :dot-scale="1" :text="appSrc" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ViewSessions from './ViewSessions.vue'
import user from '../../api/acl/user.js'
export default {
  components: {
    ViewSessions
  },
  data() {
    return {
      productSelectItem: [],
      dialogVueQr: false,
      appSrc: '',
      readonlyInput: false,
      dialogDelect: false,
      textDelect: '',
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      validateRules: {
        // code: [
        //   { required: true, trigger: 'change', message: '请输入订单编号' }
        // ],
        startTime: [
          {
            required: true,
            message: '请选择计划开始时间：',
            trigger: 'change'
          }
        ],
        endTime: [
          {
            required: true,
            message: '请选择计划完成时间：',
            trigger: 'change'
          }
        ],
        product: [{ required: true, trigger: 'change', message: '请选择产品' }],
        productNum: [
          { required: true, trigger: 'change', message: '请输入产品数量' }
        ],
        salesman: [
          { required: true, trigger: 'blur', message: '请选择业务员' }
        ]
      },
      orderList: [],
      dialogFormVisible: false,
      dialogFormValue: '',
      productList: [
        {
          value: '1',
          label: '产品1'
        }
      ],
      salesmanList: [
        {
          value: '1',
          label: '张三'
        }
      ],
      order: {
        startTime: '',
        endTime: '',
        product: '',
        code: '',
        productNum: '',
        salesman: ''
      },
      s1electOrder: {
        orgerId: '',
        startTime: '',
        endTime: '',
        salesman: ''
      },
      delectId: ''
    }
  },
  // 监听上面文本框搜索
  watch: {
    dialogFormVisible(val) {
      console.log(val)
      if (val == true) {
        this.listProduct()
      }
    }
  },

  created() {},
  mounted() {
    this.listOrder()
  },
  methods: {
    changeProduct(val) {
      console.log(val)
      const list = this.productSelectItem
      this.productSelectItem = []

      for (let i = 0; i < val.length; i++) {
        const obj = {}
        if (list.length > 0) {
          const value = list.some((item) => {
            return item.id == val[i]
          })
          if (value) {
            list.some((item) => {
              if (item.id == val[i]) {
                this.productSelectItem.push(item)
              }
            })
          } else {
            obj.id = val[i]
            obj.amount = ''
            this.productSelectItem.push(obj)
          }
        } else {
          obj.id = val[i]
          obj.key = ''
          this.productSelectItem.push(obj)
        }
      }
      console.log(this.productSelectItem)
    },
    seeVueQr(val) {
      this.dialogVueQr = true
      this.appSrc = val.id + ''
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.deleteFlag == 1) {
        return 'warning-row'
      }
      return ''
    },
    delectClick() {
      if (this.textDelect == '') {
        this.$message({
          message: '请输入删除理由',
          duration: 1000
        })
        return
      }
      user.deleteOrder({
        deleteFlag: 1,
        id: this.delectId,
        deleteRemark: this.textDelect
      }).then((response) => {
        this.delectId = ''
        this.textDelect = ''
        this.dialogDelect = false
        this.$message({
          message: '删除成功',
          duration: 1000
        })
        this.listOrder()
      })
    },
    delect(val) {
      this.delectId = val.id
      this.textDelect = ''
      this.dialogDelect = true
    },
    fetchData(val) {
      this.page = val
      this.listOrder()
    },
    beginDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.order.endTime) {
            // 如果结束时间不为空，则小于结束时间
            return new Date(self.order.endTime).getTime() < time.getTime()
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      }
    },
    processDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.order.startTime) {
            // 如果开始时间不为空，则结束时间大于开始时间
            return new Date(self.order.startTime).getTime() > time.getTime()
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      }
    },
    closeDialog() {
      this.order = {
        id: '',
        code: '',
        startTime: '',
        endTime: '',
        product: '',
        productNum: '',
        salesman: ''
      }
      this.productSelectItem = []
      this.$refs.order.resetFields()
    },
    // 产品列表
    listProduct() {
      user
        .listProduct({
          limit: 10000,
          page: 1
        })
        .then((response) => {
          this.productList = response.list
        })
    },
    // 新增，修改，删除
    insertOrder(val) {
      debugger
      if (val.id == '' || val.id == null || val.id == undefined) {
        user.insertOrder(val).then((response) => {
          this.dialogFormVisible = false
          this.$message({
            message: '新增成功',
            duration: 1000
          })
          this.listOrder()
        })
      } else {
        user.updateOrder(val).then((response) => {
          this.dialogFormVisible = false
          this.$message({
            message: '修改成功',
            duration: 1000
          })
          this.listOrder()
        })
      }
    },
    append(val) {
      console.log(this.productSelectItem)
      for (let i = 0; i < this.productSelectItem.length; i++) {
        if (this.productSelectItem[i].amount == '' || this.productSelectItem[i].amount == null || this.productSelectItem[i].amount == undefined) {
          this.$message({
            message: '请谈些产品编号对应为' + this.productSelectItem[i].id + '的数量',
            duration: 1000
          })
          return
        }
      }
      console.log(this.order.startTime)
      this.$refs[val].validate((valid) => {
        if (valid) {
          this.insertOrder({
            id: this.order.id,
            productList: this.productSelectItem,
            // amount: this.order.productNum,
            // category: this.order.product, // 类别
            // code: this.order.code, // 订单编号
            // "completedAmount": 0,//产品总数
            // "completedCategory": 0,//产品种类
            // "createBy": 0,
            // "createDt": "",
            // "deleteFlag": 0,
            endTime: this.order.endTime, // 预计结束时间
            // "id": '',
            // "qrcode": "string",//订单二维码
            salesman: this.order.salesman, // 业务员
            // "salesmanId": 0,
            startTime: this.order.startTime // 预计开始时间
            // "updateBy": 0,
            // "updateDt": "",
            // "uploadTime": ""//上穿日期
          })
        }
      })
    },
    restData() {
      this.dialogFormVisible = false
      this.dialogFormValue = ''
    },
    listOrder() {
      user
        .listOrder({
          id: this.s1electOrder.orgerId,
          endDate: this.s1electOrder.endTime,
          limit: this.limit,
          page: this.page,
          salesman: this.s1electOrder.salesman,
          startDate: this.s1electOrder.startTime
        })
        .then((response) => {
          
          this.total = response.total
          this.orderList = response.list
        })
    },

    selected(val) {
      this.s1electOrder = val
      this.page = 1
      this.listOrder()
    },
    add() {
      this.dialogFormVisible = true
      this.dialogFormValue = '新增订单'
      this.readonlyInput = false
    },
    seeOrder(val) {
      this.$router.push({ path: '/orderProductDetails', query: { id: val.id }})
    },
    seeDeleteItem(val) {
      this.dialogFormVisible = true
      this.dialogFormValue = '查看订单'
      this.readonlyInput = true
      this.order = {
        id: val.id,
        startTime: val.startTime,
        endTime: val.endTime,
        product: val.category,
        productNum: val.amount,
        code: val.code,
        salesman: val.salesman
      }
    },
    upload(val) {
      this.dialogFormVisible = true
      this.dialogFormValue = '修改订单'
      this.readonlyInput = false
      this.order = {
        id: val.id,
        startTime: val.startTime,
        endTime: val.endTime,
        product: val.category,
        productNum: val.amount,
        code: val.code,
        salesman: val.salesman
      }
    }
  }
}
</script>
<style>
.el-table .warning-row {
    background:#ff02027a;
  }
</style>
